package unimelb.discussiontracker.twitter.service.integration;

import java.util.Date;

import org.apache.log4j.Logger;

import unimelb.discussiontracker.twitter.data.dao.IHashTagDao;
import unimelb.discussiontracker.twitter.data.dao.IHashTagRankingDao;
import unimelb.discussiontracker.twitter.data.dao.IIntervalDao;
import unimelb.discussiontracker.twitter.data.entity.HashTagEntity;
import unimelb.discussiontracker.twitter.data.entity.HashTagRanking;
import unimelb.discussiontracker.twitter.data.entity.IntervalEntity;
import unimelb.discussiontracker.twitter.data.entity.TopicEntity;

public class TopHashTagParser extends AbstractFileProcessor {

    private static final Logger logger = Logger.getLogger(TopHashTagParser.class);

    private IIntervalDao intervalDao;

    private IHashTagDao hashTagDao;

    private IHashTagRankingDao hashTagRankingDao;

    public void setIntervalDao(IIntervalDao intervalDao) {
        this.intervalDao = intervalDao;
    }

    public void setHashTagDao(IHashTagDao hashTagDao) {
        this.hashTagDao = hashTagDao;
    }

    public void setHashTagRankingDao(IHashTagRankingDao hashTagRankingDao) {
        this.hashTagRankingDao = hashTagRankingDao;
    }

    @Override
    protected void processLine(String line, TopicEntity masterTopic) {
        try {
            final String[] tokens = line.split("  ")[0].split(" ");

            final Date start = dateFormat.parse(tokens[0]);
            final Date end = dateFormat.parse(tokens[1]);
            final int strength = Integer.parseInt(tokens[2]);
            final String tagValue = tokens[3].substring(1);

            HashTagEntity tag = hashTagDao.findByValue(tagValue);
            if (tag == null) {
                tag = new HashTagEntity();
                tag.setValue(tagValue);

                hashTagDao.save(tag);
            }

            final IntervalEntity interval = intervalDao.findByStartEnd(start, end);

            HashTagRanking tagRanking = hashTagRankingDao.findByTagValueTopicAndIntervalId(tagValue, masterTopic.getId(), interval.getId());
            if (tagRanking == null) {
                tagRanking = new HashTagRanking();
                tagRanking.setHashTag(tag);
                tagRanking.setInterval(interval);
                tagRanking.setTopic(masterTopic);
                tagRanking.setStrength(strength);

                hashTagRankingDao.save(tagRanking);
            } else {
                tagRanking.setStrength(strength);

                hashTagRankingDao.save(tagRanking);
            }
        } catch (Exception e) {
            logger.error("Invalid line: " + line, e);
        }
    }

}
